package com.peycash.monitoring.servicio.impl;

import java.math.BigDecimal;
import java.util.List;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.peycash.monitoring.dominio.Sms;
import com.peycash.monitoring.persistencia.PersistenciaException;
import com.peycash.monitoring.persistencia.dao.SMSDAO;
import com.peycash.monitoring.servicio.SMSServicio;
import com.peycash.monitoring.servicio.ServicioException;
import com.peycash.monitoring.utils.Constantes;
import com.peycash.monitoring.ws.SMSSender;

@Service
public class SMSServicioImpl implements SMSServicio{

	@Autowired
	private SMSDAO daoSMS;
	@Autowired
	private SMSSender smsSender;
	
	@Override
	@Transactional(readOnly=true)
	public BigDecimal count() throws ServicioException{
		try {
			BigDecimal count = daoSMS.count();
			return count;
		} catch (PersistenciaException e) {
			throw new ServicioException("Error en count:"+e.getMessage(), e);
		}
	}
	
	@Override
	@Transactional(readOnly=true)
	public List<Sms> findPendings() throws ServicioException{
		try{
			List<Sms> list = daoSMS.findPendings();
			return list;
		} catch (PersistenciaException e) {
			throw new ServicioException("Error en findPendings:"+e.getMessage(), e);
		}
	}
	
	@Override
	public String sendSms(String noCel, String message) throws ServicioException{
		try{
			String response = smsSender.sendSMS(noCel, message);
			return response;
		}catch(Exception e){
			throw new ServicioException("Error en findPendings:"+e.getMessage(), e);
		}
	}
	
	@Override
	@Transactional
	public void updateSMS(Sms sms) throws ServicioException{
		try{
			daoSMS.update(sms);
		} catch (PersistenciaException e) {
			throw new ServicioException("Error en findPendings:"+e.getMessage(), e);
		}
	}
	
	@Override
	@Transactional
	public void updateSmsClienteRegistrado(String noCel) throws ServicioException{
		try{
			List<Sms> listSms = daoSMS.findByNoCelEnvia(noCel);
			for(Sms s : listSms){
				s.setNumEnvStatus(Constantes.SMS_NUM_ENVIA_STATUS_REGISTRADO);
				daoSMS.update(s);
			}
		}catch (PersistenciaException e) {
			throw new ServicioException("Error en updateSmsClienteRegistrado:"+e.getMessage(), e);
		}
	}
}
